Moment.js Transform

A plugin for moment.js that lets you manipulate dates through patterns.

Download GitHub Project Current version: v1.0.0

Wouldn't it be useful to manipulate a date using patterns? Don't you find it annoying to always have to set hours, minutes, seconds and milliseconds to zero to drop the time part of a date? Want to set the configuration of one of your component to YtD or -30 days using a simple string?

Those are the use cases this plugin aims to answer.


Current time is:


Transformed time is:


First, download it:

Then add the plugin after the moment.js library:

<script src="./lib/moment/moment.min.js"></script>
<script src="./lib/moment-transform/moment-transform.min.js"></script>


This plugin provides one additional method to all Moment instances. Its signature is as follows:

momentInstance.transform(value[, patterns][, strict])


In a pattern, each group of the same letter (i.e. YYYY) will match [+-]?\d+. If no sign is present, it will set the value of the corresponding part of the date (i.e. year). If there is a sign, it will add or substract the value to the corresponding part of the date.

More information on the accepted pattern can be found in the format() documentation.

In everycase, the method will return a new Moment instance. If a pattern has been matched, it will return the new date. If none could be match or if the Moment instance was already invalid, it will return an invalid date. This can easily be checked by using the isValid() method.